package com.ck.demo.web;

import com.ck.demo.entity.Dept;
import com.ck.demo.entity.Emp;
import com.ck.demo.service.DeptService;
import com.ck.demo.service.EmpService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.validation.Valid;
import java.util.List;

@Controller
public class EmpController {

    @Resource
    EmpService empService;

    //注入部门得业务层
    @Resource
    DeptService deptService;

    //调到查询所有
    @RequestMapping("/emp/list")
    public String list(Model model){
        List<Emp> list = empService.list();
        model.addAttribute("empList",list);
        for (Emp emp : list) {
            emp.getBirthday();
        }
        return "list";
    }

    //跳转到添加员工页面
    @RequestMapping("/emo/toAddEmp")
    public String toUpdate(Model model){
        List<Dept> deptList = deptService.listDept();
        for (Dept dept : deptList) {
            System.out.println(dept.getDeptno());
        }
        model.addAttribute("deptList",deptList);
        return "addEmp";
    }

    //添加员工
    @PostMapping("/emp")
    public Object add(@Valid Emp emp, BindingResult bindingResult, Model model){
        if(bindingResult.hasErrors()){
            return new RuntimeException("后台验证失败");
        }
        int i = empService.addEmp(emp);
        if (i>0){
            //添加成功
            System.out.println("添加成功");
            return "redirect:/emp/list";
        }else {
            throw new RuntimeException("添加员工失败");
        }

    }

    //跳转到修改页面
    @RequestMapping("/emo/toUpdateEmp")//@RequestParam排除空值
    public String toupdate(@RequestParam Integer empno,Model model){
        Emp emp = empService.queryById(empno);
        List<Dept> deptList = deptService.listDept();
        model.addAttribute("deptList",deptList);
        model.addAttribute("emp",emp);
        return "updateEmp";
    }

    //修改员工
    @PutMapping("/emp")
    public Object update(@Valid Emp emp, BindingResult bindingResult, Model model){
        if(bindingResult.hasErrors()){
            return new RuntimeException("后台验证失败");
        }
        int i = empService.updateEmp(emp);
        if (i>0){
            //添加成功
            System.out.println("修改成功");
            return "redirect:/emp/list";
        }else {
            throw new RuntimeException("修改员工失败");
        }

    }


}
